﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace TorBrowserUpdater
{
    public class VersionParser
    {
        public const string VersionRegex = @"\d+\.\d+(\.\d+)?(-\d+)?(\.\d)?";
        public const string BetaVersionRegex = @"\d+\.\d+\.\d+(-beta|-rc)?-\d+(-pt\d+)?";
        //public const string ChangelogVersionRegex = @"Tor Browser Bundle \((" + VersionRegex + @")?)\);";

        private readonly string _language;
        private string _changelogPath;

        public VersionParser(string language)
        {
            _language = language;
        }

        public string ParseCurrentVersion()
        {
            BuildChangelogPath();

            if (!File.Exists(_changelogPath))
                return null;

            return ReadTBBVersion();
        }

        public string ParseStringContainingVersion(string text)
        {
            var match = Regex.Match(
                text, 
                StartupOptions.UsePluggableTransports ? BetaVersionRegex : VersionRegex);
            return match.Success ? match.Value : null;
        }

        private void BuildChangelogPath()
        {
            _changelogPath = Path.Combine(
                PathHelper.GetUncompressedTBBFolderPath(_language),
                "Docs",
                "ChangeLog.txt");
        }

        private string ReadTBBVersion()
        {
            using(var reader = File.OpenText(_changelogPath))
            {
                string firstLine = reader.ReadLine();
                if (firstLine == null)
                    return null;
                var match = Regex.Match(firstLine, VersionRegex);
                if(!match.Success)
                {
                    match = Regex.Match(firstLine, BetaVersionRegex);
                }
                return !match.Success ? null : match.Value;
            }
        }

    }
}
